#include "hwMqttHandler.h"
#include "hxMqttConfig.h"
#include "ScnsInclude.h"
#include "hwAdc.h"
#include "rtc.h"

void hxMqttConnectHandler(void)
{
    scnsDelayMs(100);
    hxMqttPublishSubscribe("hxmqtt/led",0);
}

void hxMqttReceiveHandler(const unsigned char*topic,unsigned int topicLen,const unsigned char*data,unsigned int dataLen)
{
    if(hxMqttStringMatch("hxmqtt/led",topic,topicLen))
    {
        if(hxMqttStringMatch("on",data,dataLen))
        {
            scnsLedSet(SCNS_LED_1,SCNS_LED_SWITCH_ON);
        }
        else if(hxMqttStringMatch("off",data,dataLen))
        {
            scnsLedSet(SCNS_LED_1,SCNS_LED_SWITCH_OFF);
        }
    }
}

static int cnt=0;

void hwMqttSend(void)
{
    ++cnt;
    char str[128];
    if(cnt>=100)
    {
        hxSPrintf(str,"%d",hwAdcResult.val);
        hxMqttPublishQos0String("hxmqtt/sensor/adc",str);
        hxSPrintf(str,"%d",scnsDht11Result[SCNS_DHT11_1].humidity);
        hxMqttPublishQos0String("hxmqtt/sensor/humidity",str);
        hxSPrintf(str,"%d",scnsDht11Result[SCNS_DHT11_1].temperature);
        hxMqttPublishQos0String("hxmqtt/sensor/temperature1",str);
        hxSPrintf(str,"%f",scnsDs18b20Result[SCNS_DS18B20_1].temperature);
        hxMqttPublishQos0String("hxmqtt/sensor/temperature2",str);
        RTC_TimeTypeDef rtcTime;
        RTC_DateTypeDef rtcDate;
        HAL_RTC_GetTime(&hrtc,&rtcTime,RTC_FORMAT_BIN);
        HAL_RTC_GetDate(&hrtc,&rtcDate,RTC_FORMAT_BIN);
        hxSPrintf(str,"%04d-%02d-%02d %02d:%02d:%02d",2000+rtcDate.Year,rtcDate.Month,rtcDate.Date,rtcTime.Hours,rtcTime.Minutes,rtcTime.Seconds);
        hxMqttPublishQos0String("hxmqtt/date",str);
        cnt=0;
    }
}
